#include "Cats/CatStates/CatState.h"
#include "Cats/CatStates/CatState_Ninja_Skill.h"
#include "Cats/BaseCat.h"
#include "Cats/CatSpriteLoader.h"
#include "Character/Character.h"
#include "Map/GameMap.h"

#include "Supporting/SoundLoader.h"
#include "Supporting/Enums/EnumSoundType.h"

int CatState_Ninja_Skill::BLINK_THRESHOLD = 600;

CatState_Ninja_Skill::CatState_Ninja_Skill(BaseCat* pCatRef):CatState(pCatRef)
{
}

CatState_Ninja_Skill::~CatState_Ninja_Skill()
{

}

void CatState_Ninja_Skill::runOnEnter()
{
	// Poof Sound
	SoundLoader::playSound(NINJA_SKILL_SOUND);

	//flipped cat sprite back to original direction
	if (_pCatRef->isFlipped())
		_pCatRef->flipCatSprite();

	_hasBlinked = false;
	playBlinkAnimation(false);
}

void CatState_Ninja_Skill::update(float timeDiff)
{
	//reduce blink animation counter
	_blinkAnimationDuration -= timeDiff;

	//have not changed position and animation ended
	if (!_hasBlinked && _blinkAnimationDuration <= 0)
	{
		//change position and start reversed blink animation
		_pCatRef->setPosition(getRandomPosition());
		_hasBlinked = true;
		playBlinkAnimation(true);
	}
	//changed position and animation ended
	else if (_hasBlinked && _blinkAnimationDuration <= 0)
	{
		_pCatRef->stopActionByTag(CatSpriteLoader::SPRITE_CAT_TAG);

		//go to chase state (since blinking will revert it to chase due to the resultant position)
		_pCatRef->setNextCatState(CAT_CHASE);
	}
}

void CatState_Ninja_Skill::onExit()
{
	// Poof Sound
	CatState::onExit();
	SoundLoader::endSound(NINJA_SKILL_SOUND);

}

void CatState_Ninja_Skill::playBlinkAnimation(bool reversed)
{
	//calculate animation duration
	_blinkAnimationDuration = CatSpriteLoader::getAnimationDuration(_pCatRef->getCatType(), CAT_ANIM_SKILL);
	//stop current cat animation
	_pCatRef->stopActionByTag(CatSpriteLoader::SPRITE_CAT_TAG);

	//play blink animation
	CCActionInterval* blinkAnimation = CatSpriteLoader::getCatAnimation(_pCatRef->getCatType(), CAT_ANIM_SKILL);
	if (reversed)
	{
		int originalTag = blinkAnimation->getTag();
		blinkAnimation = blinkAnimation->reverse();
		blinkAnimation->setTag(originalTag);
	}

	_pCatRef->runAction(blinkAnimation);

}

CCPoint CatState_Ninja_Skill::getRandomPosition()
{
	//random a lane
	CCPoint randomPosition = _pGameMapRef->getRandomCatStartPoint();

	//random an X value. X value is between right of character and right of screen
	randomPosition.x = arc4random() % ((int)(_pGameMapRef->getScreenWidth() - _pCharRef->getPositionX())) + _pCharRef->getPositionX();
	if (randomPosition.x < _pGameMapRef->getScreenWidth()/2)
		randomPosition.x += BLINK_THRESHOLD; //don't get too near the character

	return randomPosition;
}

